package com.damai.pay.alipay;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.citywithincity.pay.OrderInfo;
import com.citywithincity.pay.PayException;
import com.citywithincity.pay.PayType;
import com.damai.pay.PayAdapter;
import com.damai.pay.PayAdapterListener;
import com.damai.pay.PayAdapterManager;
import com.damai.pay.PayInfo;

public class AliPayAdapter implements PayAdapter<AliPayOrder> {

	private AliPayModel model;
	private PayAdapterListener listener;
	private String key;
	public AliPayAdapter(String partner, String seller, String privateKey, 
			String safeKey,String key){
		this(partner, seller, privateKey, safeKey, key, null);
	}
	public AliPayAdapter(String partner, String seller, String privateKey, 
			String safeKey,String key,PayAdapterListener listener){
		model = new AliPayModel(partner, seller, privateKey, safeKey);
		this.key = key;
		PayAdapterManager.register(key, this);
		this.listener = listener;
	}
	
	
	
	
	
	@Override
	public Object prePay(AliPayOrder order, HttpServletRequest request) throws PayException, IOException {
		return model.prePay(order.getOutId(), order.getTitle(), order.getAliPayFee(), PayAdapterManager.getNotifyUrl(key));
	}

	@Override
	public void refund(AliPayOrder order) throws PayException, IOException {
	
	}
	
	private void echoFail(HttpServletResponse response) throws IOException{
		response.getWriter().print("fail");
	}
	
	private void echoSuccess(HttpServletResponse response) throws IOException{
		response.getWriter().print("success");
	}

	@Override
	public void onServerNotify(HttpServletRequest request, HttpServletResponse response) {
		
		try {
			OrderInfo info = model.parseOrder(request);
			if(info==null){
				echoFail(response);
			}else{
				if(listener!=null)listener.onPaySuccess(PayType.PayType_ALIPAY, info.getOrderId(), info.getPlatId(),
						info.getPayTime(), null);
				echoSuccess(response);
			}
		} catch (Exception e) {
			try {
				echoFail(response);
			} catch (IOException e1) {
				
			}
		}
	}

	@Override
	public PayInfo getPayInfo(AliPayOrder order, Map<String, Object> json) throws PayException, IOException {
		String info = (String) json.get("info");
		return model.parse(order.getOutId(), info);
		
	}

}
